package com.example.toutiao.ui.fragment;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.toutiao.R;
import com.example.toutiao.adapter.CartAdapter;
import com.example.toutiao.db.CartItem;
import com.example.toutiao.db.DatabaseHelper;
import com.example.toutiao.db.Product;

import java.util.ArrayList;
import java.util.List;

public class CartFragment extends Fragment {

    private RecyclerView recyclerView;
    private CartAdapter cartAdapter;
    private List<CartItem> cartItemList;
    private Button btnCheckout;
    private DatabaseHelper db;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_cart, container, false);
        recyclerView = view.findViewById(R.id.recycler_cart);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));

        db = new DatabaseHelper(getContext());

        cartItemList = new ArrayList<>();
//        cartItemList.add(new CartItem(1, 2));  // 假设商品ID为1，数量为2
//        cartItemList.add(new CartItem(2, 1));  // 假设商品ID为2，数量为

        cartAdapter = new CartAdapter(getContext(), cartItemList, db);
        recyclerView.setAdapter(cartAdapter);

        btnCheckout = view.findViewById(R.id.btn_checkout);
        btnCheckout.setOnClickListener(v -> {
            // 计算总金额
            double totalAmount = 0;
            for (CartItem item : cartItemList) {
                Product product = item.getProduct(db);
                totalAmount += product.getPrice() * item.getQuantity();
            }
            // 显示结算对话框
            CheckoutDialogFragment dialog = new CheckoutDialogFragment(cartItemList, totalAmount);
            dialog.show(getFragmentManager(), "CheckoutDialog");
        });

//        Button btnClearCart = view.findViewById(R.id.btn_clear_cart);
//        btnClearCart.setOnClickListener(v -> {
//            // 清空购物车
//            cartItemList.clear();
//            cartAdapter.notifyDataSetChanged();
//        });
//
        return view;
    }
}
